package client.socket;

import base.BaseValue;
import server.socket.bean.ESocket;
import server.socket.bean.Message;
import server.util.InfoUtils.Info;
import server.util.InfoUtils.InfoUtil;
import server.util.MyUtils;

import java.io.IOException;

public class ChatClient {
    private ESocket socket;
    private ChatClient instance;

    public ChatClient getInstance() {
        return instance;
    }

    //构造方法，传入端口号BaseValue.chatPort
    public ChatClient(int port) throws IOException {
        socket = new ESocket(BaseValue.host, port);
        newThread.start();
    }

    //接受消息的线程
    Thread newThread = new Thread(() -> {
        try {
            while (true) {
                Info info = MyUtils.fromJson(socket.readUTF(), Info.class);
                System.out.println("收到" + info);
                //信息在这里接收，已经转化为message
                Message message = MyUtils.fromJson(info.getData().toString(), Message.class);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    });

    //发送消息，message需要自己设置
    public void send(Message message) {
        try {
            Info info = InfoUtil.getInfo(message);
            socket.writeUTF(MyUtils.toJson(info, 2));
            System.out.println("发送" + info.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //用户首先注册表示上线
    public void register(int userId) {
        try {
            socket.writeUTF(MyUtils.toJson(InfoUtil.getInfo(2, "注册", userId)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
